package common;

import io.github.bonigarcia.wdm.WebDriverManager;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;

public class Utils {
    public static WebDriver driver=null;
    public static String DetailUrl = "http://8.137.19.140:9090/blog_detail.html?blogId=19170";

    public WebDriverWait wait=null;

    //构造方法   先请求url
    public Utils(String url) {
        //调用driver对象  默认为空
        driver =createDriver();
        wait=new WebDriverWait(driver,Duration.ofSeconds(2));
        driver.get(url);
    }
    //获取驱动对象
    public static WebDriver createDriver(){
        //非空 不需要重新下载
        if(driver==null){
            //下载驱动
           // WebDriverManager.chromedriver().avoidBrowserDetection().setup();
            WebDriverManager.chromedriver().setup();
            ChromeOptions options =new ChromeOptions();
            //允许访问全部链接
            options.addArguments("--remote-allow-origins=*");
            //创建驱动对象
            driver =new ChromeDriver(options);

            driver.manage().window().maximize();
            //隐式等待
            driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
        }
        return driver;
    }

    //屏幕截图
    public void ScreenShot(String str) throws IOException {
        //屏幕截图文件目录
        // ./src/test/java/images/
        //                        /2025-03-02/
        //                                    /test01_03372010.png
        //                                    /test02_03382010.png
        //                        /2025-03-03/
        SimpleDateFormat sim1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sim2 = new SimpleDateFormat("HHmmssSS");//时分秒毫秒

        String dirTime = sim1.format(System.currentTimeMillis());//生成时间
        String fileTime = sim2.format(System.currentTimeMillis());
        //创建文件名 test01_03372010.png   路径 + dirtime + /  + 方法名 + _ + filetime +  .png
        String filename = "./src/test/java/images/" + dirTime + "/" + str + "_" + fileTime + ".png";
        //调用selenium屏幕截图方法
        File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);  //强转 输出文件类型
        FileUtils.copyFile(srcFile, new File(filename));//文件以图片形式放置

    }


    // 退出浏览器
    public static void quit() {
        if (driver != null)
            driver.quit();
    }
}
